package com.shanghaionstar.login.register.presenter;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.ExceptionUtil;
import com.onstar.cn.mag.joinme.CatpchaEntity;
import com.onstar.cn.mag.joinme.RegisterResponseEntity;
import com.onstar.cn.mag.joinme.RegisterToVisitorResponse;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.login.register.iview.IJoinMeView;
import com.shanghaionstar.login.register.service.JoinMeService;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.weight.CommonInputLayout;

import java.util.Locale;

import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by 7828wc on 16/7/1.
 */
public class JoinMePresenter extends BasePresenter<RegisterResponseEntity> {
    private IJoinMeView joinMeView;
    private JoinMeService service;
    private CatpchaEntity cacheCatpcha = null;

    public JoinMePresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView<RegisterResponseEntity> view) {
        super.setView(view);
        this.joinMeView = (IJoinMeView) view;
        service = new JoinMeService(view.onActivity());
    }

    public void getCaptchaImage() {
        subscription = service.checkIsNeedCaptcha(cacheCatpcha).flatMap(new Func1<CatpchaEntity, Observable<?>>() {
            @Override
            public Observable<?> call(CatpchaEntity catpchaEntity) {
                if (catpchaEntity != null) {
                    //joinMeView.showCaptchaView(true);
//                    供缓存使用
                    cacheCatpcha = catpchaEntity;
                    return service.getImageCaptcha(catpchaEntity.getCaptchaId());
                }
                //joinMeView.showCaptchaView(false);
                return null;
            }
        }).subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        //获取到验证码byte
                        joinMeView.showCaptchaImage((byte[]) o);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //抛出Error异常
                        joinMeView.onResponseError((OnStarException) throwable);
                    }
                });
    }

    /**
     * 首次进入直接注册(或者首次重新获取验证码)，不需要输入图片验证码
     */
    public void registerOwnerByVinOrGovId(final String vinOrGovId, final boolean isUpgradeOwner, final String password, final String verifyCode, final String userPhone, final String userEmail) {
        if (CommonUtil.isNull(vinOrGovId)) {
            joinMeView.verifyInputResult(false);
            return;
        }
        joinMeView.verifyInputResult(true);
        joinMeView.setLoading(true);
        String vin = "", govId = "";
        if (CommonUtil.isVin(vinOrGovId)) {
            vin = vinOrGovId.toUpperCase(Locale.CHINA);
        } else {
            govId = vinOrGovId;
        }
        Observable<?> observable = isUpgradeOwner ? service.visitorCheckAndUpgrade(cacheCatpcha, govId, vin, false) :
                service.registerOwner(cacheCatpcha, govId, vin, !CommonUtil.isNull(password) ?
                                JoinMeConstants.OperationType.CHECKREGCODE : JoinMeConstants.OperationType.INVOKEREGCODE,
                        verifyCode, password, userPhone, userEmail);
        subscription = observable.subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        if (o instanceof RegisterResponseEntity) {
                            //注册为车主
                            joinMeView.onReponseSuccess((RegisterResponseEntity) o);
                        } else if (o instanceof RegisterToVisitorResponse) {
                            //升级为车主
                            joinMeView.onResponseUpgradeSuccess((RegisterToVisitorResponse) o);
                        }
                        joinMeView.setLoading(false);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //抛出Error异常
                        joinMeView.onResponseError((OnStarException) throwable);
                        joinMeView.setLoading(false);
                    }
                });
    }


    public void registerOwnerByVinOrGovIdWithOutCatpcha(final String vinOrGovId, String captchaValue,
                                                        final boolean isUpgradeOwner, final String password,
                                                        final String verifyCode, final String userPhone,
                                                        final String userEmail, final String... names) {
        if (CommonUtil.isNull(vinOrGovId)) {
            joinMeView.verifyInputResult(false);
            return;
        }
        joinMeView.verifyInputResult(true);
        joinMeView.setLoading(true);
        String vin = "", govId = "";
        if (CommonUtil.isVin(vinOrGovId)) {
            vin = vinOrGovId.toUpperCase(Locale.CHINA);
        } else {
            govId = vinOrGovId;
        }
        service.registerOwner(cacheCatpcha, govId, vin,
                !CommonUtil.isNull(password) ? JoinMeConstants.OperationType.CHECKREGCODE : JoinMeConstants.OperationType.INVOKEREGCODE,
                verifyCode, password, userPhone, userEmail, names != null && names.length != 0 ? names[0] : "", names != null && names.length > 1 ? names[1] : "")
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
                if (!isUpgradeOwner) {
                    joinMeView.onReponseSuccess((RegisterResponseEntity) o);
                } else {
                    joinMeView.onResponseUpgradeSuccess((RegisterToVisitorResponse) o);
                }
                joinMeView.setLoading(false);
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                //抛出Error异常
                joinMeView.onResponseError((OnStarException) throwable);
                joinMeView.setLoading(false);
            }
        });
    }

    public void getCode(final String vinOrGovId,
                        final boolean isUpgradeOwner, final String password,
                        final String verifyCode, final String userPhone,
                        final String userEmail, final String... names) {
        if (CommonUtil.isNull(vinOrGovId)) {
            joinMeView.verifyInputResult(false);
            return;
        }
        joinMeView.verifyInputResult(true);
        joinMeView.setLoading(true);
        String vin = "", govId = "";
        if (CommonUtil.isVin(vinOrGovId)) {
            vin = vinOrGovId.toUpperCase(Locale.CHINA);
        } else {
            govId = vinOrGovId;
        }
        service.registerOwner(null, govId, vin,
                !CommonUtil.isNull(password) ? JoinMeConstants.OperationType.CHECKREGCODE : JoinMeConstants.OperationType.INVOKEREGCODE,
                verifyCode, password, userPhone, userEmail, names != null && names.length != 0 ? names[0] : "", names != null && names.length > 1 ? names[1] : "")
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
                if (!isUpgradeOwner) {
                    joinMeView.onReponseSuccess((RegisterResponseEntity) o);
                } else {
                    joinMeView.onResponseUpgradeSuccess((RegisterToVisitorResponse) o);
                }
                joinMeView.setLoading(false);
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                //抛出Error异常
                joinMeView.onResponseError((OnStarException) throwable);
                joinMeView.setLoading(false);
            }
        });
    }

    /**
     * @param vinOrGovId
     * @param captchaValue
     * @param isUpgradeOwner 是否为升级为车主
     */
    public void registerOwnerByVinOrGovId(final String vinOrGovId, String captchaValue, final boolean isUpgradeOwner, final String password, final String verifyCode, final String userPhone, final String userEmail, final String... names) {
        if (CommonUtil.isNull(vinOrGovId)) {
            joinMeView.verifyInputResult(false);
            return;
        }
        joinMeView.verifyInputResult(true);
        if (isRequiredCaptchaImage()) {
            if (cacheCatpcha != null && cacheCatpcha.isRequired() && CommonUtil.isNull(captchaValue)) {
                joinMeView.verifyCaptchaResult(joinMeView.onActivity().getString(R.string.input_user_info_not_null));
                return;
            }
            joinMeView.verifyCaptchaResult("");
            joinMeView.setLoading(true);
            cacheCatpcha.setCaptchaInput(captchaValue);
            subscription = service.checkImageCaptcha(cacheCatpcha.getCaptchaId(), captchaValue).flatMap(new Func1<String, Observable<?>>() {
                @Override
                public Observable<?> call(String response) {
                    if (!CommonUtil.isNull(response)) {
                        String vin = "", govId = "";
                        if (CommonUtil.isVin(vinOrGovId)) {
                            vin = vinOrGovId.toUpperCase(Locale.CHINA);
                        } else {
                            govId = vinOrGovId;
                        }
                        return isUpgradeOwner ? service.visitorCheckAndUpgrade(cacheCatpcha, govId, vin, true, names != null && names.length != 0 ? names[0] : "", names != null && names.length > 1 ? names[1] : "") :
                                service.registerOwner(cacheCatpcha, govId, vin,
                                        !CommonUtil.isNull(password) ? JoinMeConstants.OperationType.CHECKREGCODE : JoinMeConstants.OperationType.INVOKEREGCODE,
                                        verifyCode, password, userPhone, userEmail, names != null && names.length != 0 ? names[0] : "", names != null && names.length > 1 ? names[1] : "");
                    } else {
                        //抛出Error异常
                        joinMeView.onResponseError(ExceptionUtil.defaultException(new NullPointerException()));
                        joinMeView.setLoading(false);
                    }
                    return null;
                }
            }).subscribeOn(mvpScheduler.backgroundThread())
                    .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<Object>() {
                        @Override
                        public void call(Object o) {
                            if (!isUpgradeOwner) {
                                joinMeView.onReponseSuccess((RegisterResponseEntity) o);
                            } else {
                                joinMeView.onResponseUpgradeSuccess((RegisterToVisitorResponse) o);
                            }
                            joinMeView.setLoading(false);
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            //抛出Error异常
                            joinMeView.onResponseError((OnStarException) throwable);
                            joinMeView.setLoading(false);
                        }
                    });

        } else {
            joinMeView.setLoading(true);
            subscription = service.checkIsNeedCaptcha(cacheCatpcha).flatMap(new Func1<CatpchaEntity, Observable<?>>() {
                @Override
                public Observable<?> call(CatpchaEntity catpchaEntity) {
                    if (catpchaEntity != null) {
//                        joinMeView.showCaptchaView(true);
                        cacheCatpcha = catpchaEntity;
                        return service.getImageCaptcha(catpchaEntity.getCaptchaId());
                    } else {
                        String vin = "", govId = "";
                        if (CommonUtil.isVin(vinOrGovId)) {
                            vin = vinOrGovId.toUpperCase(Locale.CHINA);
                        } else {
                            govId = vinOrGovId;
                        }
                        return isUpgradeOwner ? service.visitorCheckAndUpgrade(cacheCatpcha, govId, vin, false) :
                                service.registerOwner(cacheCatpcha, govId, vin, !CommonUtil.isNull(password) ?
                                                JoinMeConstants.OperationType.CHECKREGCODE : JoinMeConstants.OperationType.INVOKEREGCODE,
                                        verifyCode, password, userPhone, userEmail, names != null && names.length != 0 ? names[0] : "", names != null && names.length > 1 ? names[1] : "");
                    }
                }
            }).subscribeOn(mvpScheduler.backgroundThread())
                    .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<Object>() {
                        @Override
                        public void call(Object o) {
                            if (o instanceof RegisterResponseEntity) {
                                //注册为车主
                                joinMeView.onReponseSuccess((RegisterResponseEntity) o);
                            } else if (o instanceof RegisterToVisitorResponse) {
                                //升级为车主
                                joinMeView.onResponseUpgradeSuccess((RegisterToVisitorResponse) o);
                            } else {
                                //获取到验证码byte
                                joinMeView.showCaptchaImage((byte[]) o);
                            }
                            joinMeView.setLoading(false);
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            //抛出Error异常
                            joinMeView.onResponseError((OnStarException) throwable);
                            joinMeView.setLoading(false);
                        }
                    });
        }
    }

    public void getVehicleUnit(String vin) {
        if (CommonUtil.isNull(vin)) {
            joinMeView.verifyInputResult(false);
            return;
        }
        joinMeView.showInfoLoading(true);
        subscription = service.getVehicleUnit(vin).subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if (joinMeView != null && view.onActivity() != null) {
                            joinMeView.showInfoLoading(false);
                            if (s != null && s.contains("true")) {
                                joinMeView.showInfoThreeView(true);
                            } else {
                                joinMeView.showInfoThreeView(false);
                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //抛出Error异常
                        if (joinMeView != null && view.onActivity() != null) {
                            joinMeView.showInfoLoading(false);
                            joinMeView.onResponseError((OnStarException) throwable);
                        }
                    }
                });

    }

    private boolean checkIsNull(CommonInputLayout inputLayout) {
        if (CommonUtil.isNull(inputLayout.getText())) {
            joinMeView.verifyResult(inputLayout, R.string.input_user_info_not_null);
            return true;
        }
        return false;
    }

    public boolean verifyUserPass(CommonInputLayout inputLayout, String userName) {
        inputLayout.setEnabled(false);
        if (checkIsNull(inputLayout)) return false;
        if (!CommonUtil.checkInput(inputLayout.getText())) {
            joinMeView.verifyResult(inputLayout, R.string.SB021_MSG031);
            return false;
        }
        if (!CommonUtil.passwordValidate(inputLayout.getText())) {
            joinMeView.verifyResult(inputLayout, R.string.userpass_error);
            return false;
        }
        if (!CommonUtil.isNull(userName) && inputLayout.getText().equals(userName)) {
            joinMeView.verifyResult(inputLayout, R.string.password_notequals_username);
            return false;
        }
        joinMeView.verifyResult(inputLayout, FinalConstants.Register.NO_ERROR);
        return true;
    }

    public boolean isRequiredCaptchaImage() {
        if (cacheCatpcha != null) {
            return cacheCatpcha.isRequired();
        }
        return false;
    }

    public void sendReport(FunctionNameFindId functionName) {
        BusinessUtil.sendReportByClickType(joinMeView.onActivity(), functionName.getStringValue());
    }

}
